#ifndef TCP_TCPCONNECTION_H
#define TCP_TCPCONNECTION_H

#include <memory>
#include <functional>
#include "InetAddress.h"
#include "Socket.h"

class TcpConnection;
typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;
typedef std::function<void(const TcpConnectionPtr &)> ConnectionCallback;
typedef std::function<void(const TcpConnectionPtr &, const char *, ssize_t)> MessageCallback;
typedef std::function<void(const TcpConnectionPtr &)> CloseCallback;

class TcpConnection : public std::enable_shared_from_this<TcpConnection>{
public:
    TcpConnection(std::string name,
                  int sockfd,
                  const InetAddress & localAddr,
                  const InetAddress & peerAddr);

    ~TcpConnection();

    void setConnectionCallback(const ConnectionCallback &connectionCallback){
        connectionCallback_ = connectionCallback;
    }

    void setMessageCallback(const MessageCallback &messageCallback){
        messageCallback_ = messageCallback;
    }

    void setCloseCallback(const CloseCallback &closeCallback){
        closeCallback_ = closeCallback;
    }

    void connectionEstablished();

    void connectDestroyed();

    std::string getName() const{
        return name_;
    }

    const InetAddress &localAddress() const { return localAddr_; }

    const InetAddress &peerAddress() const { return peerAddr_; }

    int fd(){
        return socket_->fd();
    }

    ConnectionCallback connectionCallback_;

private:
    enum StateE{kConnecting, kConnected, kDisconnected};
    // 状态枚举值

    void setState(StateE s){
        state_ = s;
    }

    void handleRead();
    void handleWrite();
    void handleClose();
    void handleError();


    bool reading_;

    std::string name_;
    // 连接名称
    StateE state_;
    // 当前连接状态
    std::unique_ptr<Socket> socket_;
    const InetAddress localAddr_;
    const InetAddress peerAddr_;

    MessageCallback messageCallback_;
    CloseCallback closeCallback_;
};

#endif //TCP_TCPCONNECTION_H
